package com.king.security.config;

import com.king.security.repository.UserRepository;
import com.king.security.security.MyPasswordEncoder;
import com.king.security.service.UserService;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author KING
 * @date 2018/8/30 18:11
 */
@Configuration
public class WebConfiguration {

    @PersistenceContext
    private EntityManager em;

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private MyPasswordEncoder myPasswordEncoder;

    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }

    @Bean
    public UserService userService() {
        UserService u = new UserService();
        u.setEm(em);
        u.setMyPasswordEncoder(myPasswordEncoder);
        u.setUserRepository(userRepository);
        return u;
    }

    @Bean
    public FilterRegistrationBean testFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("MyFilter");
        registration.setOrder(1);
        return registration;
    }

    public class MyFilter implements Filter {
        @Override
        public void destroy() {
            System.out.println("我的过滤器---destroy");
        }

        @Override
        public void doFilter(ServletRequest srequest, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) srequest;
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            System.out.println("我的过滤器,url :" + request.getRequestURI());
            filterChain.doFilter(srequest, response);
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
            System.out.println("我的过滤器---init");
        }
    }
}